//
//  ByUIAppGuideVC.m
//  oc_knowledge
//
//  Created by pro on 17/1/12.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIAppGuideVC.h"

// video
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h>

static NSString *versionKey = @"version_key";

#pragma mark - 缓存类
@interface ByCacheGuideHandle : NSObject
// 缓存字符串
+ (void)setStr:(NSString *)str key:(NSString *)key;
// 读取字符串
+ (NSString *)strForKey:(NSString *)key;
@end

@implementation ByCacheGuideHandle
// 缓存字符串
+ (void)setStr:(NSString *)str key:(NSString *)key {
    
    // 保存
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:key];
    // 同步
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 读取字符串
+ (NSString *)strForKey:(NSString *)key {
    
    //读取
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    return str;
}
@end

#pragma mark - 引导页控制器
@interface ByUIAppGuideVC ()

// data
// 定时器
@property (nonatomic, strong) NSTimer *timer;
// 倒计时
@property (nonatomic, assign) CGFloat downTime;

// 图片数组数组
@property (nonatomic, copy) NSArray *imageNames;
// 视频URL
@property (nonatomic, strong) NSURL *videoURL;


// view
// scrollView
@property (nonatomic, strong) UIScrollView *scroll;
// 进入首页按钮
@property (nonatomic, strong) UIButton *enterButton;
// 倒计时按钮
@property (nonatomic, strong) UIButton *timerButton;
// 播放器
@property (nonatomic, strong) MPMoviePlayerController *player;

// 回调
@property (nonatomic, copy) void(^enterBlock)();
@end

@implementation ByUIAppGuideVC
- (void)dealloc {
    
    [self.timerButton removeObserver:self forKeyPath:@"hidden" context:nil];
}
#pragma mark - 全局方法
// 是否应该展示引导页面
+ (BOOL)needShowGuide{
    
    // 获取当前的版本号
    NSString *versionCurrent = APP_VERSION;
    // 读取本地版本号
    NSString *versionLocal = [ByCacheGuideHandle strForKey:versionKey];
    // 存在本地版本记录，且和当前系统版本一致，则不需要展示引导页面
    if (versionLocal != nil && [versionCurrent isEqualToString:versionLocal]) {
        return NO;
    } else {
        // 保存当前开启app的版本号
        [ByCacheGuideHandle setStr:versionCurrent key:versionKey];
        
        return YES;
    }
}
/** 创建滚动图片引导界面
 *  @param imageNames 图片名数组
 *  @param videoURL 视频URL
 *  @param enterBlock 跳转按钮的事件
 *  @param configurationBlock 配置回调，按钮的位置等
 *  @param duration 倒计时时间
 */
+ (instancetype)appGuideVCWithImageNames:(NSArray *)imageNames
                                videoURL:(NSURL *)videoURL
                              enterBlock:(void (^)())enterBlock
                           configuration:(void (^)(UIButton *enterButton, UIButton *timerButton))configurationBlock
                           timerDuration:(CGFloat)duration {
    
    ByUIAppGuideVC *guideVC = [[ByUIAppGuideVC alloc] init];
    
    if (!imageNames) {
        NSMutableArray *temp = [NSMutableArray array];
        NSString *prefix = @"Guide_image";
        int index = 1;

        while (true) {
            
            NSString *imageName = [NSString stringWithFormat:@"%@%i", prefix, index];
            UIImage *image = [UIImage imageNamed:imageName];
            if (image == nil) {
                break;
            }
            
            [temp addObject:imageName];
            index ++;
        }
        
        // 在没有视频的情况下，不容许引导页图片一张都没有
        if (temp.count == 0 && videoURL == nil) {
            [UIAlertView showWithTitle:@"错误" message:@"引导页至少需要一张图片，明明规则如下：Guide_image1，Guide_image2...以此类推" cancelButtonTitle:@"好" otherButtonTitles:nil tapBlock:nil];
            return guideVC;
        }
        
        imageNames = temp.copy;
    }
    
    // 设置图片数组
    guideVC.imageNames = imageNames;
    
    // 设置视频链接
    guideVC.videoURL = videoURL;
    
    // 倒计时<=0，默认为5秒
    if (duration <= 0) {
        duration = 5;
    }
    guideVC.downTime = duration;
    
    // 设置滑动视图
    [guideVC setupScroll];
    
    // 设置定时器
    [guideVC setupTimers];

    // 保存新版本
    [guideVC saveVersion];
    
    // 设置回调事件
    guideVC.enterBlock = enterBlock;
    
    // 配置按钮信息
    configurationBlock(guideVC.enterButton, guideVC.timerButton);
    
    return guideVC;
}


#pragma mark - 懒加载
- (UIScrollView *)scroll {
    
    if (!_scroll) {
        _scroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _scroll.showsVerticalScrollIndicator = NO;
        _scroll.showsHorizontalScrollIndicator = NO;
        _scroll.pagingEnabled = YES;
        [self.view addSubview:_scroll];
    }
    return _scroll;
}
- (UIButton *)enterButton {
    
    if (!_enterButton) {
        _enterButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _enterButton.frame = CGRectMake(0, 0, 120, 40);
        [_enterButton addTarget:self action:@selector(enter) forControlEvents:UIControlEventTouchUpInside];
        _enterButton.x = SCREEN_WIDTH / 2;
        _enterButton.y = SCREEN_HEIGHT - 100;
        
        UIImage *enterImage = [UIImage imageNamed:@"Guide_enter"];
        if (enterImage) {
            [_enterButton setImage:enterImage forState:UIControlStateNormal];
            _enterButton.height = _enterButton.width * (enterImage.size.height / enterImage.size.width);
        } else {
            _enterButton.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
            _enterButton.titleLabel.font = FONT(18);
            [_enterButton setTitle:@"进入" forState:UIControlStateNormal];
            _enterButton.layer.cornerRadius = 5;
        }
    }
    return _enterButton;
}
- (UIButton *)timerButton {
    
    if (!_timerButton) {
        _timerButton.superview.userInteractionEnabled = YES;
        _timerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _timerButton.frame = CGRectMake(0, 0, 80, 30);
        _timerButton.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        _timerButton.titleLabel.font = FONT(14);
        [_timerButton setTitle:[NSString stringWithFormat:@"跳过(%.0lf)", self.downTime] forState:UIControlStateNormal];
        [_timerButton addTarget:self action:@selector(enter) forControlEvents:UIControlEventTouchUpInside];
        _timerButton.top = 20;
        _timerButton.right = SCREEN_WIDTH - 20;
    }
    return _timerButton;
}

#pragma mark - create view 
- (void)setupScroll {
    
    // 如果有图片，先创建图片
    if (self.imageNames.count != 0) {
        [self.imageNames enumerateObjectsUsingBlock:^(NSString *imageName, NSUInteger idx, BOOL *stop) {
            
            // 创建页面视图
            UIImageView *pageView = [[UIImageView alloc] initWithFrame:CGRectMake(idx * self.scroll.width, 0, self.scroll.width, self.scroll.height)];
            pageView.image = [UIImage imageNamed:imageName];
            pageView.tag = idx;
            [self.scroll addSubview:pageView];
        
        }];
    }
    
    if (self.videoURL) {
        
        // 添加播放器
        self.player = [[MPMoviePlayerController alloc] initWithContentURL:self.videoURL];
        self.player.view.frame = CGRectMake(self.scroll.subviews.count * self.scroll.width, 0, self.scroll.width, self.scroll.height);
        [self.scroll addSubview:self.player.view];
        [self.player setShouldAutoplay:YES];
        [self.player setControlStyle:MPMovieControlStyleNone];
        [self.player setRepeatMode:MPMovieRepeatModeOne];
        [UIView animateWithDuration:2 animations:^{
            [self.player prepareToPlay];
        }];
    }
    
    NSInteger pages = self.scroll.subviews.count;
    self.scroll.contentSize = CGSizeMake(pages * self.scroll.width, 0);
    [self.scroll.subviews.lastObject addSubview:self.enterButton];
    self.scroll.subviews.lastObject.userInteractionEnabled = YES;
    
    
}
- (void)setupTimers {
    
    [self.view addSubview:self.timerButton];
    // 监听AppDelegate中对倒计时按钮的hidden是否操作，如果隐藏，则需要把定时器关闭
    [self.timerButton addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew context:nil];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fire];
}
- (void)timerAction {
    
    self.downTime -= 0.01;
    if (self.downTime <= 0) {
        [self enter];
        return;
    }
    NSString *timerButtonText = [NSString stringWithFormat:@"跳过(%i)", (int)self.downTime + 1];
    [self.timerButton setTitle:timerButtonText forState:UIControlStateNormal];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"hidden"]) {
        BOOL isHidden = [change[NSKeyValueChangeNewKey] boolValue];
        if (isHidden) {
            [self.timer invalidate];
            self.timer = nil;
        }
    }
}

- (void)setupVideoPlayer {
    
    // 添加播放器
    self.player = [[MPMoviePlayerController alloc] initWithContentURL:self.videoURL];
    [self.view addSubview:self.player.view];
    self.player.shouldAutoplay = YES;
    [self.player setControlStyle:MPMovieControlStyleNone];
    self.player.repeatMode = MPMovieRepeatModeOne;
    [self.player.view setFrame:self.view.bounds];
    self.player.view.alpha = 0;
    [UIView animateWithDuration:2 animations:^{
        self.player.view.alpha = 1;
        [self.player prepareToPlay];
    }];
    
    // 添加按钮
    [self.view addSubview:self.enterButton];
}

#pragma mark - 其他
- (void)saveVersion {
    
    // 系统直接读取的版本号
    NSString *versionCurrent = APP_VERSION;
    // 保存版本号
    [ByCacheGuideHandle setStr:versionCurrent key:versionKey];
}

#pragma mark - 点击事件
- (void)enter {
    
    // 关闭定时器
    [self.timer invalidate];
    self.timer = nil;

    // 让appDelegate中执行进入操作
    self.enterBlock();
}
@end
